<script lang="ts" setup>
import {computed, ref, watch} from "vue"
import {debounce} from "@/utils/debounce";
import type {SuggestItem} from "@/types/search";
import {useSearchHistoryStore} from "@/stores/searchHistory";
import {onReachBottom} from "@dcloudio/uni-app";
import {getUserListByKeywordApi} from "@/api/user";
import type {FollowPreItem, User} from "@/types/user";
import {useUserStore} from "@/stores/user";

// 获取顶部安全距离
const {safeAreaInsets} = uni.getSystemInfoSync()
const pageQuery = defineProps<{
  keyword?: string
}>()

onReachBottom(() => {
  if (isNoMore.value) {
    return
  }
  page.value++
  onSearch()
})
const keyword = ref(pageQuery.keyword || '')
const page = ref(1)
const pageSize = ref(10)
const userList = ref<FollowPreItem[]>([])
const loading = ref(false)
const total = ref(0)
// 搜索
/*搜索历史*/
const searchHistoryStore = useSearchHistoryStore()
// 用户输入框输入
const suggestList = ref<SuggestItem[]>([])
const onInputSearch = debounce(async () => {
  if (!keyword.value) {
    return
  }
  // 这里延迟发送
  // const res = await getUserListApi(keyword.value);
  // suggestList.value = res.data
}, 200, {leading: true, trailing: false})

//高亮显示——返回数据与关键词对比相同高亮
/**
 *  高亮显示
 * @param keyword 匹配关键词
 * @param data 待匹配数据
 */
const highlight = (keyword: string, data: string) => {
  let regex = new RegExp(keyword, 'gi');
  let match;
  while ((match = regex.exec(data)) !== null) {
    let startIndex = match.index;
    let endIndex = regex.lastIndex;
    let highlightedText = data.substring(startIndex, endIndex);
    let replacement = `<span style="color: #39c5bb;">${highlightedText}</span>`;
    data = data.substring(0, startIndex) + replacement + data.substring(endIndex);
    regex.lastIndex = startIndex + replacement.length; // 避免死循环
  }
  return data;
}

// 用户搜索框搜索或者点击搜索
const onSearch = async () => {

  if (!keyword.value) {
    return
  }
  if (isNoMore.value) {
    userList.value = []
  }
  loading.value = true
  // 根据用户输入的id和用户名搜索用户
  const res = await getUserListByKeywordApi(keyword.value, page.value, pageSize.value)
  loading.value = false
  total.value = res.data.total
  if (res.data.data === null || res.data.data.length === 0) {
    isNoMore.value = true
    return
  }
  res.data.data.forEach((item: User) => {
    const user: FollowPreItem = {
      avatar: item.avatarURL,
      followed: false,
      intro: item.individualResume,
      name: item.username,
      userId: item.userID
    }
    if (userList.value.length < 1) {
      userList.value = [user]
    } else {
      userList.value.push(user)
    }
  })
  if (userList.value.length >= res.data.total - 1) {
    isNoMore.value = true
  }
}

const isNoMore = ref(false)
//清空历史
const popup = ref()
const onClearHistory = () => {
  if (!searchHistoryStore.searchHistory) {
    return
  }
  //删除前提示
  popup.value.open()
}

//返回
const goBack = () => {
  uni.navigateBack()
}
const userStore = useUserStore()
const goUserHomepage = (userId: number) => {
  let type = 1
  if (userId === userStore.userInfoData?.userID) {
    type = 0
  }
  uni.navigateTo({url: '/subPkg/userHomepage/userHomepage?type=' + type + '&userId=' + userId})
}
watch(keyword, (newVal) => {
  if (newVal.length === 0) {
    userList.value = []
    isNoMore.value = false
    page.value = 1
  }
})
const isEmpty = computed(() => {
  return userList.value.length === 0 && keyword.value.length !== 0 && isNoMore.value
})
</script>

<template>
  <view :scroll-y="true" class="search-container">
    <view :style="{ paddingTop: safeAreaInsets?.top! + 20 + 'px', fontSize: '16px' }"
          class="navbar  text-white padding-lr-sm" style="position: fixed">
      <view class="flex justify-between align-center" style="gap: 20rpx;width: 100%">
        <view class="cuIcon-back flex justify-center align-center " style="width: 44rpx;height: 44rpx;"
              @click="goBack"></view>
        <view class="nav-item" style="flex-grow: 1">
          <input v-model="keyword" :focus="true"
                 placeholder="用户名/用户id" placeholder-style="color:#999999" style="width: 100%;color: #333333"
                 @confirm="onSearch"/>
        </view>
        <view class="nav-item"
              style="font-size:30rpx;color: #f1f1f1;flex-direction: row;min-width: 60rpx;margin-right: 15px"
              @click="onSearch">
          搜索
        </view>
      </view>
    </view>
    <view :style="{ paddingTop: safeAreaInsets?.top! + 80 + 'px'}"
          style="width: 100%;min-height: 100px;position: relative">
      <view v-for="(item,index) in userList" :key="item.userId" class="msg-list-item"
            @click="goUserHomepage(item.userId)">
        <text v-if="keyword&&index===0" :style="{ paddingTop: safeAreaInsets?.top! + 70 + 'px'}"
              class="text-gray" style="margin-left: 10px;position: absolute;top: 0px;left: 10px">共&nbsp;“
          <text style="color: #39c5bb">{{ total }}</text>
          ”&nbsp;条结果
        </text>
        <view class="msg-common msg-avatar">
          <uv-avatar :src="item.avatar" mode="aspectFill" size="50"></uv-avatar>
        </view>
        <view class="msg-common msg-content ">
          <view class="msg-content-item text-black text-df">{{ item.name }}</view>
          <view class="msg-content-text text-gray text-sm">
            {{ item.intro.length > 20 ? item.intro.substring(0, 19) + '...' : item.intro }}
          </view>
        </view>
        <view class="msg-common padding-right-lg" style="border-bottom: #e6e6e6 1px solid;">
          <view class="cu-btn radius bg-gradual-awGreen">主页</view>
        </view>
      </view>
      <view v-show="loading" style="width: 100%;height: 80px;padding-top: 50px">
        <aw-loader></aw-loader>
      </view>
    </view>
    <view v-show="isNoMore&&!isEmpty" class="flex justify-center padding-lg text-gray" style="width: 100%">
      没有更多了哟~
    </view>
    <view v-if="isEmpty" class="flex justify-center align-center flex-column"
          style="width: 100%;height: 70vh">
      <image mode="aspectFit" src="/static/empty-data.png" style="width: 250px;height: 250px"></image>
      <view class="text-gray text-lg">这里什么都没有哟ヾ(≧▽≦*)o</view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search-container {
  width: 100%;

  /* #ifdef H5 */
  background-color: #fff;
  /* #endif */
}

.navbar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #39c5bb;
  padding-bottom: 10px;

  // 固定
  z-index: 999;
  background-image: url('@/static/circle.png');
  background-size: 80% 200%;
  background-repeat: repeat-x;
  // 右上角
  background-origin: border-box;
  // 背景图片位置
  background-position: left -10px bottom 50px;


  .nav-item {
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 35px;
      height: 35px;
    }

    input {
      border: #3ebed3 1px solid;
      border-radius: 35rpx;
      background-color: rgba(255, 255, 255, 0.3);
      height: 70rpx;
      padding-left: 70rpx;
      color: rgba(255, 255, 255, 0.83);
      background-image: url('@/static/search.png');
      background-repeat: no-repeat;
      background-position: 10px center;
      background-size: 20px;

      &::placeholder {
        color: #fff;
      }
    }
  }

  .img {
    border-radius: 50%;
    border: #3ebed3 1px solid;
    background-color: #3ebed3;
    width: 28px;
    height: 28px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

}

.history {
  display: flex;
  flex-direction: column;
  padding: 10px 10px 0 10px;

  width: 100%;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px;
    font-size: 32rpx;
    color: #b9b9b9;
    border-bottom: #b9b9b9 1rpx solid;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .history-item {
      font-size: 14px;
      padding: 10px 15px;
      background-color: rgba(57, 197, 187, 0.75);
      color: #ffffff;
      font-weight: 400;
      margin: 10px;
      border-radius: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: none;
    }
  }
}

.suggest-list {
  position: absolute;
  //top: 65px;
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  z-index: 999;

  .suggest-item {
    border-bottom: #f1f1f1 1px solid;
    display: flex;
    padding: 10px 10px 10px 10px;
  }
}

.recommend {
  width: 100%;
  padding: 30rpx;
}

.msg-list {
  margin-top: 20rpx;
  background-color: #fff;
  width: 100%;

  &-item {
    width: 100%;
    height: 160rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10rpx;

    .msg-common {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .msg-avatar {
      flex: 2;
    }


    .msg-content {
      flex: 6;
      border-bottom: #e6e6e6 1px solid;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: center;
      gap: 8px;
    }
  }
}
</style>
